package com.zhangyujun.bysj.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhangyujun.bysj.common.exception.GuiguException;
import com.zhangyujun.bysj.manager.mapper.SysRoleUserMapper;
import com.zhangyujun.bysj.model.dto.system.AssignRoleDto;
import com.zhangyujun.bysj.model.dto.system.LoginDto;
import com.zhangyujun.bysj.model.dto.system.SysUserDto;
import com.zhangyujun.bysj.model.entity.system.SysUser;
import com.zhangyujun.bysj.model.vo.common.ResultCodeEnum;
import com.zhangyujun.bysj.model.vo.system.LoginVo;
import com.zhangyujun.bysj.manager.mapper.SysUserMapper;
import com.zhangyujun.bysj.manager.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 张于宴
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {
        //获取输入的验证码 redis的key名称
        String key = loginDto.getCodeKey();
        String captcha = loginDto.getCaptcha();
        //根据redis的key获取到验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key);
        //比较输入的验证码
        if (StrUtil.isEmpty(redisCode)||!StrUtil.equalsIgnoreCase(redisCode,captcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //验证成功 删除redis里面的验证码
        redisTemplate.delete("user:validate" + key);
        //1 获取提交用户名 LoginDto获取到
        String userName = loginDto.getUserName();
        //2 根据用户名查询用户信息sys_user表
        SysUser sysUser = sysUserMapper.selectByUserName(userName);
        //3 如果根据用户名查不到对应信息 用户不存在 返回错误信息
        if (sysUser == null){
//            throw new RuntimeException("用户名不存在");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);

        }
        //4 如果根据用户名查到对应信息 用户存在
        //5 获取输入的密码 比较输入的密码和数据库密码是否一致
        String database_password = sysUser.getPassword();
        //把输入的密码进行加密与数据库密码对比
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //比较
        if (!database_password.equals(input_password)){
//            throw new RuntimeException("密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //6 如果一致 登录成功 如果密码不一致登录失败
        //7 登陆成功 生成用户唯一的Token
        String token = UUID.randomUUID().toString().replace("-", "");
        //8 把登录成功的用户信息放到redis里面
        //key : token value : 用户信息     key  value 超时时间
        redisTemplate.opsForValue().set("user:login"+token, JSON.toJSONString(sysUser),7, TimeUnit.DAYS);
        //9 返回loginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }
    //获取用户信息
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login"+token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login"+token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum , pageSize);
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto) ;
        PageInfo pageInfo = new PageInfo(sysUserList) ;
        return pageInfo;
    }

    //用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
        //判断用户名是否重复
        SysUser dbsUserName = sysUserMapper.selectByUserName(sysUser.getUserName());
        if (dbsUserName != null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //密码加密
        String md5Password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5Password);
        //设置status状态  1可用  0不可用
        sysUser.setStatus(1);
        sysUser.setAvatar("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        sysUserMapper.save(sysUser);
    }

    //用户修改
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    //用户删除
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    @Override
    public void doAssign(AssignRoleDto assignRoleDto) {
        //1 根据用户id删除用户之前分配的角色
        sysRoleUserMapper.deleteByUserId(assignRoleDto.getUserId());
        //2 重新分配角色
        List<Long> roleIdList = assignRoleDto.getRoleIdList();
        //遍历得到每个角色ID
        for (Long roleId : roleIdList) {
            sysRoleUserMapper.doAssign(assignRoleDto.getUserId(),roleId);
        }
    }
}
